<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    protected $_id;
        
    /**
     * Authenticates a user.
     * @return boolean whether authentication succeeds.
     */

    public function authenticate()
    {
        $record=Usuari::model()->findByAttributes(array('nomUsuari'=>$this->username));

        if($record===null)
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        //else if($record->contrasenya!==$this->password)
        else if($record->contrasenya!==md5($this->password))
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        else {
            //Guardar dades usuari
            $this->_id= $record->idUsuari;
            
            //Registrar entrada
            $auth=Yii::app()->authManager;
            if(!$auth->isAssigned($record->rol,$this->_id))
            {
                if($auth->assign($record->rol,$this->_id))
                {
                    Yii::app()->authManager->save();
                }
            }
                        
            //Netejar codi d'error
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId() {
        return $this->_id;
    }
}